package com.gitee.huanminabc.utils_tools.config_refresh.file;

import com.gitee.huanminabc.jcommon.file.FileUtil;
import com.gitee.huanminabc.jcommon.test.PathUtil;
import com.gitee.huanminabc.utils_tools.config_refresh.enums.ConfigFileTypeEnum;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;

@Component
public class PropertiesFileRead implements ConfigFileRead {

    @Override
    public ConfigFileTypeEnum fileType() {
        return ConfigFileTypeEnum.PROPERTIES;
    }

    public Properties read() throws IOException {
        Properties properties = readPeer();
        properties.putAll(readConfig());
        return properties;
    }

    public Properties readPeer() throws IOException {
        String home = PathUtil.getCurrentProjectAbsolutePath() ;
        List<String> files = FileUtil.getFiles(home);
        Properties propertiesAll = new Properties();
        for (String file : files) {
            if (file.endsWith(".properties")) {
                Properties properties = new Properties();
                properties.load(Files.newInputStream(Paths.get(file)));
                propertiesAll.putAll(properties);
            }
        }
        return propertiesAll;
    }

    public Properties readConfig() throws IOException {
        String home = PathUtil.getCurrentProjectAbsolutePath() + File.separator+ "config";
        List<String> files = FileUtil.getFiles(home);
        Properties propertiesAll = new Properties();
        for (String file : files) {
            if (file.endsWith(".properties")) {
                Properties properties = new Properties();
                properties.load(Files.newInputStream(Paths.get(file)));
                propertiesAll.putAll(properties);
            }
        }
        return propertiesAll;
    }
}
